package com.yds.longlinks.client;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.HandlerThread;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.yds.developtools.utils.YDSIpHelper;

import java.net.InetAddress;

/**
 * 作者:     YDS
 * 创建时间: 2022/11/29 20:59
 * 页面描述:
 */
public class MinaClientService extends Service {
    private MinaThread mThread;

    @Override
    public void onCreate() {
        super.onCreate();
        mThread = new MinaThread("mina", getApplicationContext());
        mThread.start();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    class MinaThread extends HandlerThread {
        private Context mContext;
        private boolean isConnection = false;
        private MinaClientConnectionManager mMinaClientConnectionManager;

        public MinaThread(String name, Context context) {
            super(name);
            this.mContext = context;

            InetAddress localIPAddress = YDSIpHelper.getLocalIPAddress();
            Log.i("YDSimon","localIPAddress = "+localIPAddress);

            MinaClientConnectionConfig minaClientConnectionConfig = new MinaClientConnectionConfig.Builder(mContext)
                    .setIp("192.168.110.161")
                    .setPort(8686)
                    .build();
            mMinaClientConnectionManager = new MinaClientConnectionManager(minaClientConnectionConfig);
        }

        @Override
        protected void onLooperPrepared() {
            for (; ; ) {
                isConnection = mMinaClientConnectionManager.connect();
                if (isConnection) break;
                try {
                    Thread.sleep(5000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        public void disConnection() {
            mMinaClientConnectionManager.disConnect();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mThread.disConnection();
        mThread = null;
    }
}
